package com.atguigu.filter;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.result.RetVal;
import com.atguigu.result.RetValCodeEnum;
import com.atguigu.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class AuthGlobalFilter implements GlobalFilter {
    @Autowired
    private RedisTemplate redisTemplate;
    //匹配条件器
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    //获取网关中的白名单
    @Value("${filter.writeList}")
    private String filterWriteList;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.网关拦截器  让直接访问sku业务界面  没有登录则权限不够
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();//这个路径就取到的是sku/getSkuInfo 比如: http://item.gmall.com/sku/getSkuInfo
        //让其中包含sku的不能单独直接进行访问
        if (antPathMatcher.match("/sku/**",path)){
            return writeDataToBrowser(exchange,RetValCodeEnum.NO_PERMISSION);
        }
        //2.用户登录了 由redis记录的IP地址 判断当前登录是否为同一IP地址 不是则提示 权限不够
        //获取用户的id
        String userId = getLoginUserId(request);
        //用户没登录时的 临时id
        String userTempId = getUserTempId(request);
        if (userId.equals("-1")){
           return writeDataToBrowser(exchange,RetValCodeEnum.NO_PERMISSION);
        }
        //3.业务中我的订单 我的购物车等等 需要登录后才能进行访问
        if (antPathMatcher.match("/order/**",path)){
            //userId为空 则提示未登录
            if (StringUtils.isEmpty(userId)){
                return writeDataToBrowser(exchange,RetValCodeEnum.NO_LOGIN);
            }
        }
        //4.网关中的白名单(比如 加入购物车) 需要登录后才能继续访问
        for (String filterWrite : filterWriteList.split(",")) {
            //包含在白名单内 用户未登录
            if (path.indexOf(filterWrite) != -1 && StringUtils.isEmpty(userId)){
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.SEE_OTHER);
                //设置完成之后重定向到登录界面
                response.getHeaders().set(HttpHeaders.LOCATION,"http://passport.gmall.com/login.html?originalUrl="+request.getURI());
                return response.setComplete();
            }
        }
        //如果用户进行登录了  将userId 和 临时id进行传递到shop-cart中  让实现后续的添加购物车等
        if (!StringUtils.isEmpty(userId) || !StringUtils.isEmpty(userTempId)){
            if (!StringUtils.isEmpty(userId)){
                request.mutate().header("userId",userId).build();
            }
            if (!StringUtils.isEmpty(userTempId)){
                request.mutate().header("userTempId",userTempId).build();
            }
            //过滤器放开  此时修改了exchange对象  将userId 和 临时id进行传递
            return chain.filter(exchange.mutate().request(request).build());
        }
        return chain.filter(exchange);
    }
    //用户没登录时的 临时id
    private String getUserTempId(ServerHttpRequest request) {
        //从redis中获取  先获取token  拼接成 user:login:token
        List<String> tokenList = request.getHeaders().get("userTempId");
        String userTempId = "";
        if (!CollectionUtils.isEmpty(tokenList)){
            userTempId = tokenList.get(0);
        }else {
            //Header 为空 则从cookie中获取
            HttpCookie tokenCookie = request.getCookies().getFirst("userTempId");
            if (tokenCookie != null){
                userTempId = tokenCookie.getValue();
            }
        }
        return userTempId;
    }

    //获取用户的id
    private String getLoginUserId(ServerHttpRequest request) {
        //从redis中获取  先获取token  拼接成 user:login:token
        String token = null;
        List<String> tokenList = request.getHeaders().get("token");
        if (!CollectionUtils.isEmpty(tokenList)){
            token = tokenList.get(0);
        }else {
            //Header 为空 则从cookie中获取
            HttpCookie tokenCookie = request.getCookies().getFirst("token");
            if (tokenCookie != null){
                token = tokenCookie.getValue();
            }
        }
        //从redis中获取用户id
        if (!StringUtils.isEmpty(token)){
            String userKey = "user:login:"+token;
            String loginInfoJson = (String)redisTemplate.opsForValue().get(userKey);
            JSONObject jsonObject = JSONObject.parseObject(loginInfoJson);
            //登录的ip
            String loginIp = jsonObject.getString("loginIp");
            //在获取当前的ip
            String gatwayIpAddress = IpUtil.getGatwayIpAddress(request);
            if (gatwayIpAddress.equals(loginIp)){
                //ip相等  再返回用户的id 防止cookie被盗
                return jsonObject.getString("userId");
            }else {
                //不相等 则返回 -1
                return "-1";
            }
        }
        return "";
    }

    //把数据写给浏览器
    private Mono<Void> writeDataToBrowser(ServerWebExchange exchange,RetValCodeEnum retValCodeEnum) {
        ServerHttpResponse response = exchange.getResponse();
        RetVal<Object> retVal=RetVal.build(null, retValCodeEnum);
        //把该retVal转换为json字符串
        byte[] retBytes = JSONObject.toJSONString(retVal).getBytes(StandardCharsets.UTF_8);
        //将字节转换为一个数据buffer 效率高
        DataBuffer dataBuffer = response.bufferFactory().wrap(retBytes);
        //设置返回给浏览器的请求头 数据类型是json字符串
        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        //把数据发射给浏览器
        return response.writeWith(Mono.just(dataBuffer));
    }
}